package com.yhny.lykj.yuhannongye.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.longsichao.lscframe.ctrl.DataManager;
import com.longsichao.lscframe.model.LSCModel;
import com.longsichao.lscframe.net.HttpConnection;
import com.longsichao.lscframe.net.NetworkHelper;
import com.longsichao.lscframe.view.LSCImageView;
import com.longsichao.lscframe.view.LSCToast;
import com.yhny.lykj.yuhannongye.R;
import com.yhny.lykj.yuhannongye.app.BaseActivity;
import com.yhny.lykj.yuhannongye.app.UserConfig;
import com.yhny.lykj.yuhannongye.model.BaseModel;
import com.yhny.lykj.yuhannongye.model.ImageModel;
import com.yhny.lykj.yuhannongye.model.SmsModel;
import com.yhny.lykj.yuhannongye.model.UserInfoModel;
import com.yhny.lykj.yuhannongye.net.NetHelper;
import com.yhny.lykj.yuhannongye.photo.ClipImageActivity;
import com.yhny.lykj.yuhannongye.photo.FileUtils;
import com.yhny.lykj.yuhannongye.photo.MultiImageSelector;
import com.yhny.lykj.yuhannongye.tools.FileUtil;
import com.yhny.lykj.yuhannongye.tools.ImageSelector;
import com.yhny.lykj.yuhannongye.tools.LCLog;
import com.yhny.lykj.yuhannongye.tools.LCSysTimeUtils;
import com.yhny.lykj.yuhannongye.tools.Tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.yhny.lykj.yuhannongye.net.NetHelper.UID;

public class UserInfoActivity extends BaseActivity {
    private TextView nameTv;
    private TextView ageTv;
    private TextView sexTv;
    private TextView idTv;
    private TextView phoneTv;
    private TextView rightTv;
    private TextView phone;
    private LSCImageView phtotIv;



    //图片返回数据
    ImageModel imageModel;
    private String url;


    /**
     * 选择的照片
     */
    private List<String> selectImages = new ArrayList<>();
    private static final int TAKE_PICTURE = 0x000001;
    private static final int REQUEST_IMAGE = 0x012;
    private static final int REQUEST_JIETU = 0x013;


    private String vipId;
    private String bridthStr;
    private DatePickerDialog date;
    private String cityId;
    private String recommendId;//推荐人id
    private String merId;//所属商家id
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        TextView topName = (TextView)findViewById(R.id.name_top_bar);
        topName.setText("个人信息");
        phtotIv = (LSCImageView)findViewById(R.id.user_photo);
        phtotIv.setOnClickListener(this);
        nameTv = (TextView)findViewById(R.id.user_name);
        ageTv = (TextView)findViewById(R.id.user_age);
        sexTv = (TextView)findViewById(R.id.user_sex);
        idTv = (TextView)findViewById(R.id.user_id_num);
        phoneTv = (TextView)findViewById(R.id.user_phone);
        rightTv = (TextView)findViewById(R.id.right_text);
        phone = (TextView)findViewById(R.id.phone);
        rightTv.setText("保存");
        rightTv.setVisibility(View.VISIBLE);
        rightTv.setOnClickListener(this);
        sexTv.setOnClickListener(this);
        phoneTv.setOnClickListener(this);
        nameTv.setOnClickListener(this);
        ageTv.setOnClickListener(this);
        idTv.setOnClickListener(this);
        findViewById(R.id.right_group).setOnClickListener(this);
        findViewById(R.id.left_group).setOnClickListener(this);
        findViewById(R.id.left_text).setOnClickListener(this);
        initDate();

        DataManager.getData(MODEL_PROCESS_0, NetHelper.User.getUserInfo(), this);
        showProgressDialog(R.string.text_loading);
    }
    /**
     * 初始化时间弹窗
     */
    private void initDate(){
        date=   new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                long time = LCSysTimeUtils.getTime(""+String.format("%d-%d-%d",year,monthOfYear+1,dayOfMonth))/1000;
                bridthStr = ""+time;
                ageTv.setText(""+String.format("%d-%d-%d",year,monthOfYear+1,dayOfMonth));
            }
        },2000,1,2);
    }
    private void takePhoto(){
        //检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //进入到这里代表没有权限.
            if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
                //已经禁止提示了
                LSCToast.show(this,"您已禁止该权限，需要重新开启");
            }else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MultiImageSelector.REQUEST_FILE);
            }
        } else {
            MultiImageSelector selector = MultiImageSelector.create();
            selector.showCamera(true);
            selector.single();
            selector.origin((ArrayList<String>)selectImages);
            selector.start(this, REQUEST_IMAGE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_text:
            case R.id.left_group:{
                finish();
                break;
            }
            case R.id.right_text:
            case R.id.right_group:{
                //修改
                String name = nameTv.getText().toString();
                String age = ageTv.getText().toString();
                String id = idTv.getText().toString();
                if (!Tools.isIdNumber(id)){
                    LSCToast.show(this,"请输入正确的身份证号码！");
                    return;
                }
                String sex = sexTv.getText().toString();
                String phone = phoneTv.getText().toString();
                String photo = url;
                DataManager.getData(MODEL_PROCESS_1, NetHelper.User.modifyUserInfo(name,bridthStr,sex,id), this);
                break;
            }
            case R.id.user_photo:{
                //上传头像

                takePhoto();


                break;
            }
            case R.id.user_name:{
                //姓名
                Intent intent = new Intent(this,EditUserActivity.class);
                intent.putExtra("edit","姓名");
                intent.putExtra("editid",1001);
                startActivityForResult(intent,1001);
                break;
            }
            case R.id.user_sex:{
                //性别
                final String[] sex = new String[]{"男", "女"};
                new AlertDialog.Builder(this)
                        .setTitle("选择性别")
                        .setSingleChoiceItems(sex, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                sexTv.setText(sex[i]);
                            }
                        })
                        .setPositiveButton("确定", null)
                        .setNegativeButton("取消", null)
                        .show();
                break;
            }
            case R.id.user_age:{
                //年龄

                if (!date.isShowing()){
                    date.show();
                }
                break;
            }
            case R.id.user_id_num:{
                //身份证号
                Intent intent = new Intent(this,EditUserActivity.class);
                intent.putExtra("edit","身份证号");
                intent.putExtra("editid",1002);
                startActivityForResult(intent,1002);
                break;
            }


            case R.id.user_address:{
                //地址
                Intent intent = new Intent(this,EditUserActivity.class);
                intent.putExtra("edit","地址");
                intent.putExtra("editid",1005);
                startActivityForResult(intent,1005);
                break;
            }


        }
        super.onClick(v);
    }

    @Override
    public boolean onModel(int caseId, LSCModel model) {
        if (super.onModel(caseId, model)) {
            dismissProgressDialog();
            return false;
        }
        switch (caseId){
            case MODEL_PROCESS_1:{
                SmsModel baseModel=(SmsModel)model;
                if (baseModel!=null&&baseModel.status==1){
                    LSCToast.show(this,"修改成功!");
                    UserConfig.setConfigUserName(nameTv.getText().toString());
                    UserConfig.setConfigUserPhotoUrl(url);
                }else{
                    LSCToast.show(this,"修改失败!");

                }
                dismissProgressDialog();
                break;
            }
            case MODEL_PROCESS_0:{
                UserInfoModel userInfoModel = (UserInfoModel)model;
                if (!isDataEmpty(userInfoModel)&&userInfoModel.status==1){
                    if (userInfoModel.data.truename==null){
                        userInfoModel.data.truename = "";
                    }

                    if (userInfoModel.data.userdate==null){
                        ageTv.setText("0");
                    }else{
                        bridthStr = userInfoModel.data.userdate;
                        ageTv.setText(""+LCSysTimeUtils.getYdmDate(userInfoModel.data.userdate,1));
                    }
                        sexTv.setText(userInfoModel.data.usersex);
                    nameTv.setText(""+userInfoModel.data.truename);
                    phoneTv.setText(""+userInfoModel.data.usertel);
                    phone.setText(""+userInfoModel.data.usertel);
                    idTv.setText(""+userInfoModel.data.userident);
                    url = userInfoModel.data.userpic;
                    UserConfig.setConfigUserPhotoUrl(url);
                    int height = getResources().getDimensionPixelOffset(R.dimen.item_comment_img);
                    int width = getResources().getDimensionPixelOffset(R.dimen.item_comment_img);
                    if (url!=null) {
                        phtotIv.setType(LSCImageView.Type.CropCircle).setPlaceHolder(R.drawable.default_user).setTargetSize(width, height).setImageURI(Uri.parse(url));
                    }else{
                        phtotIv.setType(LSCImageView.Type.CropCircle).setImageResource(R.drawable.default_user);
                    }

                }else{
                    LSCToast.show(this,"加载失败！");
                }
                dismissProgressDialog();
                break;
            }
        }
        dismissProgressDialog();
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case MultiImageSelector.REQUEST_FILE:
                if(grantResults.length >0 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    //用户同意授权
                    takePhoto();
                }else{
                    //用户拒绝授权
                    LSCToast.show(this,"您已禁止该权限，需要重新开启");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //相机相册选回掉
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case TAKE_PICTURE: {
                    //拍照
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    String path = FileUtil.saveBitmap(bm, fileName);
                    if (!FileUtil.isBland(path)) {
                        selectImages.add(path);
                    }
                }
                break;
                case REQUEST_IMAGE: {
                    //相册
                    selectImages = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);

                    //裁剪图片
                    gotoClipActivity(Uri.fromFile(new File(selectImages.get(0))));
                    break;
                }
                case REQUEST_JIETU:{
                    final Uri uri = data.getData();
                    if (uri == null) {
                        return;
                    }
                    showProgressDialog(R.string.text_image_loading);
                    if (selectImages.size()>0){
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                upLoadImage(uri);//上传图片
                            }
                        },1000);

                    }


                    break;
                }
            }
        }
        if (data!=null) {
            String value = data.getStringExtra("editid");
            String id = data.getStringExtra("edit");
            switch (resultCode) {
                case 1001: {
                    nameTv.setText(value);
                    break;
                }
                case 1002: {
                    idTv.setText(value);
                    break;
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    if (imageModel!=null&&imageModel.status == NET_SUSSEC&&imageModel.src!=null) {
                        Resources resources = getResources();
                        int height = resources.getDimensionPixelOffset(R.dimen.item_image_height);
                        int width = resources.getDimensionPixelOffset(R.dimen.item_image_height);
                        url = imageModel.src;
                        if (!TextUtils.isEmpty(url)){
                            phtotIv.setType(LSCImageView.Type.CropCircle).setPlaceHolder(R.drawable.default_user).setTargetSize(width, height).setImageURI(Uri.parse(url));
                        }else{
                            phtotIv.setType(LSCImageView.Type.CropCircle).setImageResource(R.drawable.default_user);
                        }
                        LSCToast.show(UserInfoActivity.this, "上传成功!");
                    } else {
                        LSCToast.show(UserInfoActivity.this, imageModel.msg);
                    }
                    dismissProgressDialog();
                    break;
                }
                case 2:{
                    LSCToast.show(UserInfoActivity.this, imageModel.msg);
                    break;
                }
            }
            return false;
        }
    });

    /**
     * 上传图片
     * @param uri
     */
    private void upLoadImage(Uri uri){
        String cropImagePath = FileUtils.getRealFilePathFromUri(getApplicationContext(), uri);
        Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);
        String uriString = cropImagePath;
        File file;
        Bitmap bitmap;
        file = new File(uriString);
        String path = file.getPath();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        bitmap = BitmapFactory.decodeFile(path, options);
        String filename = "" + System.currentTimeMillis()+".jpg";
        LCLog.e("filename = "+filename);

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("userid", UserConfig.getConfigUserId());
        builder.addFormDataPart("userpic", filename, RequestBody.create(NetworkHelper.MEDIA_TYPE_JPG, ImageSelector.compressImage(bitmap)));

        Request request = new Request.Builder().url(NetHelper.Tools.postImage().getUrl()).post(builder.build()).build();
        HttpConnection.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        dismissProgressDialog();
                        LSCToast.show(UserInfoActivity.this, "上传失败!");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String string = response.body().string();
                if (!Tools.isGoodJson(string)){
                    LSCToast.show(UserInfoActivity.this, "服务器请求失败！");
                }else {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    LCLog.e("string = "+string);
                    imageModel = gson.fromJson(string, ImageModel.class);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);


                }
            }
        });

    }

    /**
     * 打开截图界面
     *
     * @param uri
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.putExtra("type", 1);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_JIETU);
    }
}
